# -*- encoding: utf-8 -*-

# Copyright 2010 István Szentandrási
# <etude-music-player@googlegroups.com>

# This file is part of Etude.
#
# Etude is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as 
# published by the Free Software Foundation, either version 3 
# of the License, or (at your option) any later version.
#
# Etude is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Etude. If not, see <http://www.gnu.org/licenses/>.

from . import _

import etude.plugins as ep
import dbus_util
import dbus

import sys
import traceback

class GnomeMediaButtons(ep.PluginExtra):
    """
    Support for gnome media buttons throught DBus. 
    """
    _short_name = "Gnome Media Buttons"
    _show_name = _("Gnome Media Buttons")
    _short_descr = _("Support for gnome media buttons throught DBus.")
    _version = "0.1"
    _unique = "Gnome_Media_Buttons-0.1" # short name + version is enough, just to identify loaded


    def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            orig = super(GnomeMediaButtons, cls)
            cls._instance = orig.__new__(cls, *args, **kw)
        return cls._instance
    
    def __init__(self, control):
        self.unloaded = False
        if hasattr(self, '_inited'):
            return
        self._inited = True
        
        ep.PluginExtra.__init__(self, control)
        if dbus_util.using_dbus():
            try:
                bus = dbus.SessionBus()
                dbusObj = bus.get_object('org.freedesktop.DBus',
                        '/org/freedesktop/DBus')
                dbusInterface = dbus.Interface(dbusObj, 'org.freedesktop.DBus')
                if dbusInterface.NameHasOwner('org.gnome.SettingsDaemon'):
                    try:
                        # mmkeys for gnome 2.22+
                        settingsDaemonObj = bus.get_object(
                                'org.gnome.SettingsDaemon', 
                                '/org/gnome/SettingsDaemon/MediaKeys')
                        settingsDaemonInterface = dbus.Interface(
                                settingsDaemonObj, 
                                'org.gnome.SettingsDaemon.MediaKeys')
                        settingsDaemonInterface.GrabMediaPlayerKeys('Etude', 0)
                    except:
                        # mmkeys for gnome 2.18+
                        settingsDaemonObj = bus.get_object(
                                'org.gnome.SettingsDaemon', 
                                '/org/gnome/SettingsDaemon')
                        settingsDaemonInterface = dbus.Interface(
                                settingsDaemonObj,
                                'org.gnome.SettingsDaemon')
                        settingsDaemonInterface.GrabMediaPlayerKeys('Etude', 0)
                    settingsDaemonInterface.connect_to_signal(
                            'MediaPlayerKeyPressed', self.action)
            except:
                traceback.print_exc(file=sys.stdout)

    def action(self, app, key):
        if self.unloaded:
            return
        if app == 'Etude':
            pb = self.control.client.playback
            if key in ('Play' , 'PlayPause', 'Pause'):
                pb.toggle()
            elif key == 'Stop':
                pb.stop()
            elif key in ('Prev', 'Previous'):
                pb.prev()
            elif key == 'Next':
                pb.next()

    def unload(self):
        ep.PluginExtra.unload(self)
        self.unloaded = True
    
